// 顶点着色器程序
let VSHADER_SOURCE =
    'attribute vec4 a_Position;\n' +
    'void main() {\n' +
    ' gl_Position = a_Position;\n' +  //设置坐标
    ' gl_PointSize = 10.0;\n' + //设置尺寸
    '}\n';

//片元着色器程序
let FSHADER_SOURCE =
    'precision mediump float;\n' +  //指定变量的范围和精度(中等精度)
    'uniform vec4 u_FragColor;\n' +
    'void main() {\n' +
    ' gl_FragColor = u_FragColor;\n' + //设置颜色
    '}\n';

function main() {
    let canvas = document.getElementById('webgl');

    let gl = getWebGLContext(canvas);
    if (!gl) {
        console.log('Failed to get the rendering context for WebGL');
        return;
    }

    //初始化着色器
    if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        console.log('Failed to initialize shaders');
        return;
    }

    //获取attribute变量的地址
    let a_Position = gl.getAttribLocation(gl.program, 'a_Position');
    if (a_Position < 0) {
        console.log('Failed to get the storage location of a_Position');
        return;
    }

    let u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');
    if (u_FragColor == 0) {
        console.log('Failed to get the storage location of u_FragColor');
        return;
    }

    //注册鼠标点击事件
    canvas.onmousedown = function (e) {
        click(e, gl, canvas, a_Position, u_FragColor);
    }

    /**指定清空<canvas>的颜色 */
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    //清空<canvas>
    gl.clear(gl.COLOR_BUFFER_BIT);
}

var g_points = [];
var g_colors = [];
function click(e, gl, canvas, a_Position, u_FragColor) {
    let x = e.clientX;
    let y = e.clientY;
    let rect = e.target.getBoundingClientRect();

    x = ((x - rect.left) - canvas.width / 2) / (canvas.width / 2);
    y = (canvas.height / 2 - (y - rect.top)) / (canvas.height / 2);
    g_points.push([x, y]);

    if (x < 0 && y < 0) { g_colors.push([1.0, 0.0, 0.0, 1.0]); }
    else if (x > 0 && y > 0) { g_colors.push([0.0, 1.0, 0.0, 1.0]); }
    else { g_colors.push([0.0, 0.0, 1.0, 1.0]); }

    gl.clear(gl.COLOR_BUFFER_BIT);

    let len = g_points.length;
    for (let i = 0; i < len; i++) {
        let xy = g_points[i];
        let rgba = g_colors[i];

        gl.vertexAttrib3f(a_Position, xy[0], xy[1], 0.0);
        gl.uniform4f(u_FragColor, rgba[0], rgba[1], rgba[2], rgba[3]);
        gl.drawArrays(gl.POINTS, 0, 1);
    }
}